﻿#include "itemview.h"
#include "ui_itemview.h"

ItemView::ItemView(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::ItemView)
{
    ui->setupUi(this);

    base_url=URL_CDN;
    viewType=VT_NULL;
    defaultSize=this->size();
    manager=new QNetworkAccessManager(this);
    //  connect(manager,&QNetworkAccessManager::finished,this,&ItemView::replyFinished);
}

ItemView::~ItemView()
{
    delete ui;
}

void ItemView::downloadUrl(const QString &url)
{
    file=new QFile(filePath);
    if(!file->open(QFile::WriteOnly))
    {
        file->deleteLater();
        return;
    }

    downloadReply= manager->get(QNetworkRequest(QUrl(url)));
    connect(downloadReply,&QNetworkReply::readyRead,this,&ItemView::fileReadyRead);
    connect(downloadReply,&QNetworkReply::finished,this,&ItemView::downloadFinish);
}

void ItemView::fileReadyRead()
{
    file->write(downloadReply->readAll());
}

void ItemView::downloadFinish()
{
    file->flush();
    file->close();
    file->deleteLater();
    downloadReply->deleteLater();

    QPixmap pix(filePath);
    if(pix.isNull())
        return;
    ui->display->setPixmap(pix);
}

void ItemView::display(const QString &detail)
{
    if(detail.isEmpty())
    {
        viewType=VT_NULL;
        return;
    }
    this->resize(defaultSize);
    if(detail.startsWith(PRE_CDN))
    {
        viewType=VT_IMG;

        QString fileName=detail;
        fileName=fileName.remove(PRE_CDN);
        filePath=P_FHS_CACHE + fileName;
        if(QFile::exists(filePath))
        {
            QPixmap pix(filePath);
            if(!pix.isNull())
                ui->display->setPixmap(pix);
            else
            {
                QFile::remove(filePath);
                ui->display->setText(QStringLiteral("正在加载图片……"));
                QString url=base_url + fileName;
                downloadUrl(url);
            }
        }
        else
        {
            ui->display->setText(QStringLiteral("正在加载图片……"));
            QString url=base_url + fileName;
            downloadUrl(url);
        }
    }
    else
    {
        viewType=VT_TEXT;
        ui->display->setText(detail);
    }
}

int ItemView::getViewType() const
{
    return viewType;
}

QImage ItemView::getImage() const
{
    QImage img{};
    const QPixmap *pix=ui->display->pixmap();
    if(!pix->isNull())
        img=pix->toImage();
    return img;
}
